local class = require 'hump.class'
local HC = require 'hardoncollider'
require 'utilities.spacephysics'
local state = require 'utilities.state'

Laser = class{
  function(self, collider, spacephysics)
    self.collider = collider
    self.physics = spacephysics
  end
}

function Laser:shoot(cx, cy, angle, speed)
  if not self:active() then
    local w, h = 2, 4
    self.rect = self.collider:addRectangle(cx-w/2, cy-h/2, w, h)
    self.rect.parent = self
    self.rect:rotate(angle)
    self.laserphysics = self.physics:newItem(0, cx, cy)
    local vx, vy = speed*math.sin(angle), speed*-1*math.cos(angle)
    self.laserphysics:accelerate(vx, vy, 1)
    self.audio = 'audio/laser.wav'
  end
end

function Laser:onCollide()
  if self.rect then
    self.collider:remove(self.rect)
    self.rect = nil
  end
  if self.laserphysics then
    self.physics:removeItem(self.laserphysics)
    self.laserphysics = nil
  end
end

function Laser:update()
  if self:active() then
    self.rect:moveTo(self.laserphysics:center())
  end
end

function Laser:active()
  return self.rect ~= nil and self.laserphysics ~= nil
end

function Laser:state()
  if self:active() then
    local cx, cy = self.rect:center()
    local px1,py1,px2,py2 = self.rect:bbox()
    local w = px2-px1
    local h = py2-py1
    local a = self.audio
    self.audio = nil
    return state.new(cx, cy, w, h, self.rect:rotation(), nil, a)
  end
end
